﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"list.h"
//传入头节点的初始化
void LTInit(LTNode** pphead) {
	*pphead = (LTNode*)malloc(sizeof(LTNode));
	if (*pphead == NULL)
	{
		perror("malloc fail!!");
		return;
	}
	(*pphead)->data = -1;//哨兵位
	(*pphead)->next = *pphead;
	(*pphead)->prev = *pphead;
}

//返回头节点的初始化
LTNode* LTinit()
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	if (phead == NULL)
	{
		perror("malloc fail!!");
		return NULL;
	}
	phead->data = -1;
	phead->next = phead->prev = phead;
	return phead;
}
LTNode* LTBuyNode(ListData x) {
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail!!");
		return NULL;
	}
	node->data = x;
	node->next = node->prev = NULL;
	return node;
}
//尾插
void LTPushback(LTNode* phead,ListData x) {
	assert(phead);
	LTNode* node = LTBuyNode(x);
	assert(node);
	node->next = phead;
	node->prev = phead->prev;
	phead->prev->next = node;
	phead->prev = node;
}
void LTPrint(LTNode* phead) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("\n");
}
//头插
void LTPushfront(LTNode* phead, ListData x) {
	assert(phead);
	LTNode* node = LTBuyNode(x);
	assert(node);
	node->next = phead->next;
	node->prev = phead;
	phead->next->prev = node;
	phead->next = node;
}

//尾删
void LTPopback(LTNode* phead) {
	assert(phead);
	//只有哨兵为不能删
	assert(phead->next != phead);
	LTNode* del = phead->prev;
    del->prev->next = phead;
	phead->prev = del->prev;
	free(del);
	del = NULL;
}

//头删
void LTPopfront(LTNode* phead) {
	assert(phead);
	assert(phead->next != phead);
	LTNode* del = phead->next;
	phead->next = del->next;
	del->next->prev = phead;
	free(del);
	del = NULL;
}

//在pos位置之后插⼊数据
void LTInsert(LTNode* pos, ListData x) {
	assert(pos);
	LTNode* node = LTBuyNode(x);
	assert(node);
	node->next = pos->next;
	node->prev = pos;
	pos->next = node;
	node->next->prev = node;
}

//找数据的位置
LTNode* LTFind(LTNode* phead, ListData x) {
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

//删除pos数据
void LTErase(LTNode* pos) {
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
	pos = NULL;
}

LTNode* LTdestory(LTNode** pphead) {
	assset(pphead);
	assert(*pphead);
	LTNode* cur = (*pphead)->next;
	while (cur != *pphead) {
		LTNode* next = cur->next;
		free(cur);
		cur == next;
	}
	free(*pphead);
	*pphead = NULL;
}